package main

import (
	"bytes"
	"fmt"
	"image"
	"image/jpeg"
	"os"

	"golang.org/x/image/draw"
)

func main() {
	data, err := os.ReadFile("art.jpeg")
	if err != nil {
		fmt.Printf("读文件出错 +%v", err)
	}
	img, err := jpeg.Decode(bytes.NewReader(data))
	if err != nil {
		fmt.Printf("jpeg解析出错 +%v", err)
	}
	var rect = img.Bounds()

	var newImg *image.RGBA
	if rect.Max.X > rect.Max.Y {
		ratio := float32(rect.Max.X) / 720.0
		newImg = image.NewRGBA(image.Rect(0, 0, 720, int(float32(rect.Max.Y)/ratio)))
	} else {
		ratio := float32(rect.Max.Y) / 720.0
		newImg = image.NewRGBA(image.Rect(0, 0, int(float32(rect.Max.X)/ratio), 720))
	}

	draw.BiLinear.Scale(newImg, newImg.Rect, img, img.Bounds(), draw.Over, nil)

	fmt.Printf("图像尺寸 +%v %+v", rect, newImg.Rect)

	file, err := os.Create("resize.jpeg")
	if err != nil {
		fmt.Printf("jpeg解析出错 +%v", err)
		return
	}

	jpeg.Encode(file, newImg, &jpeg.Options{80})

	var jpegData bytes.Buffer

	jpeg.Encode(&jpegData, newImg, &jpeg.Options{80})
	fmt.Printf("jpeg长度 +%v", len(jpegData.Bytes()))
}
